<?php
/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);


namespace app\common\service;


use app\common\exception\CommonServiceException;

class EnvService
{
    public function refreshApiJwtKey()
    {
        $env    = base_path() . '/.env';
        $prefix = 'API_JWT_KEY=';
        $search = $prefix . getenv('api_jwt_key');
        $key    = sha1(uniqid('api_jwt_key', true));
        return file_put_contents($env, str_replace($search, $prefix . $key, file_get_contents($env)));
    }

    /**
     * @param false $force
     * @return string
     * @throws CommonServiceException
     */
    public function createEnv(bool $force = false): string
    {
        $example = base_path() . '/.env.example';
        $env     = base_path() . '/.env';

        if ($force || !file_exists($env)) {
            if (!file_exists($example)) {
                throw new CommonServiceException('.example.env文件不存在');
            }
            $copy = copy($example, $env);
            if (!$copy) {
                throw new CommonServiceException('生成.env文件失败');
            }
        }


        return $env;
    }
}